/*2S7LXljdWdGhrCxZ1MFl4nbo76lbmNV/zj9vAsZ4TsJjt35I/W4VBwuu/33I9fcb*/
/* 盘点单卡片界面 */
import React, { Component } from 'react';
import { ajax, createPage, base, createPageIcon, cardCache, toast } from 'nc-lightapp-front';
import {
    buttonClick,
    StepOne,
    StepTwo,
    StepThree,
    initTemplate,
    AnewAllot,
    InventoryResult,
    backToList,
    DetailList,
    pageInfoClick,
    commit
} from './events';
import { pageConfig } from './const';
import './index.less';
import constant from '../constants';
import ampub from 'ampub';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import CreateNCUploade from 'uap/common/components/CreateNCUploade';
import * as actions from './events/buttonClick';
const { components, commonConst, utils } = ampub;
const { cardUtils, multiLangUtils, closeBrowserUtils, listUtils } = utils;
const { getTitleName } = listUtils;
const { getMultiLangByID } = multiLangUtils;
const { createCardPaginationArea, creatCardSocket } = cardUtils;
const { CommonKeys } = commonConst;
const { linkQueryConst } = CommonKeys;
const { ApprovalTrans, CrossServiceCardBtn } = components;
const { SagaStatus } = ampub.commonConst.SagaConst;
const { NCStep, NCAffix, NCBackBtn, NCDiv } = base;
const { pagecode, dataSource, area, formId, pkField, bill_type } = pageConfig;
const { NCSteps } = NCStep;
const { createNCUploader } = CreateNCUploade;
const steps = [
    { title: getMultiLangByID('201203004A-000046') /* 确定盘点范围*/ },
    { title: getMultiLangByID('201203004A-000047') /* 分配盘点人*/ },
    { title: getMultiLangByID('201203004A-000048') /* 确认*/ }
];

/**
 * 资产盘点
 * @author : liuzjk
 */
class Maininfo extends Component {

    constructor(props) {
        props.use.search(constant.AREA.STEP.INVENTORY_RANGE);
        props.use.form(formId, constant.AREA.STEP.INVENTORY_DATE);
        props.use.cardTable(constant.AREA.STEP.ANEWALLOT, constant.AREA.STEP.DETAIL_LIST);
        props.use.editTable(constant.AREA.STEP.ALLOT_CHECKUSER);
        super(props);
        // 是否从列表跳转的
        this.isFromList = 'false';
        // 单据号
        this.bill_code = null;
        // 盘点结果组织
        this.result_pk_org = '';
        // 时间戳
        this.ts = '';
        // 盘点范围
        this.rangeAreaData = null;
        // 标识符
        this.signature = '';
        /* 盘点结果 */
        this.checkResult = '0';
        // 临时存储分配盘点人数据
        this.tempEditTableDatas = null;
        // 临时存储未分配盘点人数据
        this.tempCardTableDatas = [];
        // 盘点类型：1：快速盘点 2：精细盘点
        this.inv_type = '2';
        this.echartsData = {
            total_num: 0,
            start_date: 0,
            end_date: 0,
            pk_org: '',
            pk_category: '',
            /* 盘点范围 */
            check_range: '',
            /* 查询区范围 */
            search_range: {},
            /**
			 * 饼图数据
			 */
            pie_data: {
                category_total: [],
                values: []
            },
            /**
			 * 盘点结果柱状图数据
			 */
            bar_data: {
                x_axis: [],
                unfinished: [],
                finished: []
            },
            /**
			 * 确定后柱状图数据
			 */
            linedata: {
                data: [],
                name: []
            },
        };
        /**
		 * 保存成功后从服务返回的数据
		 */
        this.childformData = {
            head: [],
            body: [],
            way: []
        };
        this.state = {
            // bill_code: '',
            pk_inventory: '',
            pk_reduce: '',
            pk_profit: '',
            pk_alter: '',
            bill_status: '', // 单据状态
            current: 0, // 步骤条对应页面的参数默认：0
            inventoryWay: 1, // 步骤二中分配盘点方式的值
            inventoryStatus: 'default',
            pk_bill: '',
            showApprove: false,
            /* 提交指派 */
            compositedisplay: false,
            compositedata: {},
            transi_type: '',
            isLeaveOrRefresh: false,
            billInfo: {
                // 单据信息
                isError: false
            },
            uploader: {},
            // 打印参数记录
            print_param: {
                type: '0', // 打印类型：0.按照盘点结果进行筛选的打印（默认）、1.按照盘点人对盘点明细筛选的打印、2.未分配盘点人列表的打印
                inventory_checkuser: '', // 计划盘点人的Pk值，默认为空
                check_result: '0', // 盘点结果的值：0.相符、1.盘盈、2.盘亏、3.不符，默认为0
            },
        };
        closeBrowserUtils.call(this, props, {
            editTable: [constant.AREA.STEP.ALLOT_CHECKUSER],
            cardTable: [constant.AREA.STEP.DETAIL_LIST]
        });
        initTemplate.call(this, props);
    }

    // 提交及指派 回调
    getAssginUsedr = (value) => {
        commit.call(this, 'SAVE', this.props, value);
    };

    // 取消 指派
    turnOff = () => {
        this.setState({ compositedisplay: false });
    };

    // 步骤条详细说明
    Ondescription = (current, index) => {
        if (index == current) {
            return getMultiLangByID('201203004A-000049');
        } else if (index < current) {
            return getMultiLangByID('201203004A-000050');
        }
    };

    /**
	 * 头部显示数据控制
	 * 		1.返回按钮
	 * 		2.标题
	 * 		3.盘点单号
	 */
    createCardTitleArea = (current) => {
        /** **************************************
		 *flag:返回按钮是否显示标识
		 *条件：查看盘点结果 或 第三步保存后 或 盘点明细（盘点结果穿透列表）
		 *		并且 非审批小应用 并且 非盘点报告穿透
		 ****************************************/
        const flag
			= ((current === 3 || current === 7)
				&& this.props.getUrlParam('scene') != linkQueryConst.SCENETYPE.approvesce)
			|| /* 非审批小应用 */ current === 6; // 盘点明细不管是审批小应用还是非审批小应用，都应该有返回按钮
        /* 单据号 是否显示 */
        const bill_code = this.bill_code;
        let titleValue = getTitleName.call(this, this.props);
        if (bill_code) {
            titleValue = `${getTitleName.call(this, this.props)}:${bill_code}`;
        }
        return (
            <div className="header-title-search-area org-content">
                {flag && (
                    <NCBackBtn
                        // className="title-search-detail"
                        onClick={() => {
                            backToList.call(this, this.props, current);
                        }}
                        fieldid="back_btn"
                    />
                )}
                {createPageIcon()}
                <span fieldid={`${getTitleName.call(this, this.props)}_title`} className="title-search-detail">
                    {titleValue}
                </span>
            </div>
        );
    };

    isQuickChanged = (value) => {
        this.inv_type = value;
    };

    socketMessageHandle = (props, msg) => {
        const billInfo = msg.refreshData && msg.refreshData[0];
        if (msg.error && billInfo) {
            const saga_status = billInfo.saga_status;
            this.setState({
                billInfo: {
                    isError: SagaStatus.errorValue === saga_status,
                    gtxid: billInfo.saga_gtxid,
                    billpk: billInfo[pkField]
                }
            });
        } else {
            // 事务通过重试或回退方式成功时，要恢复按钮显示控制逻辑
            this.setState({ billInfo: { isError: false } });
        }
        // 更新列表态缓存
        const cachedData = cardCache.getCacheById(billInfo[pkField], constant.DATASOURCE);
        if (cachedData) {
            const headValue = cachedData.head[constant.AREA.CARD.BODY_HEAD].row[0].values;
            Object.keys(billInfo).forEach((key) => {
                if (headValue[key]) {
                    headValue[key].value = billInfo[key];
                }
            });
            cardCache.updateCache(
                pkField,
                billInfo[pkField],
                cachedData,
                constant.AREA.CARD.BODY_HEAD,
                constant.DATASOURCE
            );
        }
    };

    //导入
    upload(v) {
        window.hh = this
        if (!v) {
            return;
        }
        let formData = new FormData();
        let dome = document.querySelector('#fileInfo')
        //加参数
        formData.append('imgFile', dome.files[0]);
        // headers['Content-Type'] == 'multipart/form-data'

        let pk_org = '';
        let result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
        if (result == null) {
            return;
        }
        pk_org = result[0].values['pk_org'].value;

        ajax({
            url: '/nccloud/fa/orginventory/excelImport.do',
            data: formData,
            headers:{'Content-Type': 'multipart/form-data', pk_org:pk_org},
            success: (res) => {
                let _this = this
                if (res &&res.success) {
                    document.querySelector('#fileInfo').value = ''
                    if (res.data['isSuccess'] === "Y") {
						let retdata = res.data['retData'];
						actions['importSuccess'].call(this, retdata);
                    } else {
                        toast({color: 'danger', content: res.data['errorMessage']});
                    }
                }
            }
        })
    }

    render() {
        const { ncmodal, button } = this.props;
        const { current, inventoryStatus, showApprove, pk_inventory, transi_type } = this.state; // 需要输出的数据
        const { createModal } = ncmodal;
        const { createButtonApp } = button;
        const isSagaError = this.state.billInfo && this.state.billInfo.isError;

        return (
            <div className="nc-bill-card fa-inventory">
                {/* <div className="nc-bill-top-area"> */}
                <NCAffix>
                    {/* 头部 header */}
                    <NCDiv
                        areaCode={NCDiv.config.HEADER}
                        className={`nc-bill-header-area nonprint${isSagaError ? ' socket-error-class ' : ''}`}
                    >
                        <div className="header-title-search-area">{this.createCardTitleArea(current)}</div>

                        {/* 按钮区 btn-area */}
                        <div className="header-button-area">
                            {/* 创建重试、回退等 saga 状态按钮 */}
                            <CrossServiceCardBtn billInfo={this.state.billInfo} />
                            {createButtonApp({
                                area: 'card_head',
                                buttonLimit: 3,
                                onButtonClick: buttonClick.bind(this),
                                popContainer: document.querySelector('.header-button-area')
                            })}
                        </div>

                        {current == 7
							&& inventoryStatus == 'confirmed'
							&& createCardPaginationArea.call(this, this.props, {
							    formId,
							    dataSource,
							    pageInfoClick
							})}
                    </NCDiv>
                </NCAffix>
                {/* </div> */}
                <div className="nc-single-table">
                    <div
                        className={`current-content-area nc-theme-area-bgc ${this.state.current === 1
							&& 'stepTwo-content-area'}`}
                    >
                        {this.state.current < 4 && (
                            <div className="step-area">
                                <NCSteps current={current}>
                                    {steps.map((item, index) => (
                                        <NCStep
                                            key={item.title}
                                            title={item.title}
                                            description={this.Ondescription(current, index)}
                                        />
                                    ))}
                                </NCSteps>
                            </div>
                        )}

                        {/* 子组件StepOne */}
                        {this.state.current === 0 && (
                            <StepOne
                                {...this.props}
                                rangeAreaData={this.rangeAreaData}
                                invType={this.inv_type}
                                isQuickChanged={this.isQuickChanged.bind(this)}
                            />
                        )}
                        {this.state.current === 1
							&& (inventoryStatus === 'confirmedAllot' || inventoryStatus === 'unAllot' ? (
							    <AnewAllot {...this.props} />
							) : (
							    <StepTwo {...this.props} echartsData={this.echartsData} that={this} />
							))}
                        {(this.state.current === 2 || this.state.current === 3) && (
                            <StepThree {...this.props} echartsData={this.echartsData} that={this} />
                        )}
                        {this.state.current === 6 && <DetailList {...this.props} that={this} />}
                        {this.state.current === 7
							&& (inventoryStatus === 'confirmedAllot' ? (
							    <AnewAllot {...this.props} />
							) : (
							    <InventoryResult {...this.props} echartsData={this.echartsData} that={this} />
							))}
                    </div>
                </div>
                {/* 确认取消框 */}
                {createModal(`${pagecode}-confirm`, { color: 'warning' })}
                {/* 审批详情 */}
                <ApproveDetail
                    show={showApprove}
                    close={() => {
                        this.setState({ showApprove: false });
                    }}
                    billtype={transi_type}
                    billid={pk_inventory}
                />
                {/* 提交及指派 */}
                {this.state.compositedisplay ? (
                    <ApprovalTrans
                        title={getMultiLangByID('amcommon-000002') /* 指派*/}
                        data={this.state.compositedata}
                        display={this.state.compositedisplay}
                        getResult={this.getAssginUsedr}
                        cancel={this.turnOff}
                    />
                ) : (
                    ''
                )}
                {/* 附件管理框 */}
                {createNCUploader.call(this, `${pagecode}-uploader`, {})}

                {/* 创建 socket 链接 */}
                {creatCardSocket.call(this, this.props, {
                    headBtnAreaCode: 'card_head', // 按钮区域编码,用于平台内部更新按钮状态
                    billpkname: pkField, // 单据主键名, 用于查询追溯
                    billtype: bill_type, // 单据类型, 用于查询追溯
                    onMessage: this.socketMessageHandle.bind(this)
                })}

            <input style={{display: 'none'}} type='file' id='fileInfo' onChange={(v) => {
                    this.upload(v)
                }}/>
            </div>
        );
    }

}

const MasterChildCardBase = createPage({
    billinfo: {
        billtype: 'grid',
        pagecode, // 页面编码
        bodycode: area.card.body_area, // 表体编码
        tabletype: 'cardTable'
    }
})(Maininfo);

export default MasterChildCardBase;

/*2S7LXljdWdGhrCxZ1MFl4nbo76lbmNV/zj9vAsZ4TsJjt35I/W4VBwuu/33I9fcb*/